/**
 * 
 */
package jnzb.control.events;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import jnzb.control.Configuration;
import jnzb.control.util.Logger;
import jnzb.model.event.Event;
import jnzb.model.event.EventTableModel;
import jnzb.model.event.EventType;
import jnzb.ui.UserInterface;

/**
 * Processes information events
 * Should actually be separate from file and delegate to file so non-UI tasks can use it too!
 * 
 * @author AA1
 * 
 */
public class InfoEventProcessorImpl implements InfoEventProcessor {

	public static final int DEBUG_LEVEL = 2;
	public static final int INFO_LEVEL = 1;
	public static final int ERROR_LEVEL = 0;

	private boolean outputToConsole = true;

	/**
	 * Info level - debug and above by default
	 */
	private int currentLevel = DEBUG_LEVEL;

	private UserInterface ui = null;
	private EventTableModel eventModel = null;
	private Logger logger=null;
	
	public InfoEventProcessorImpl(UserInterface ui, Logger logger) {
		this.ui = ui;
		this.eventModel = new EventTableModel();
		this.logger = logger;

		// Wire the event model into the JTable in the panel
		ui.getInfoPanel().setInfoModel(this.eventModel);

	
		// Read log level and set if its a sensible value
		int logLevel = Configuration.getInstance().getLogLevel();
		if (logLevel > 0 && logLevel <= DEBUG_LEVEL){
			currentLevel=logLevel;
		}
	}

	private void addEvent(Event event) {
		this.eventModel.addEvent(event);
		// Tells the UI to display the latest info
		this.ui.getInfoPanel().updateInfo();
		if (outputToConsole) {
			System.out.println(event);
		}
		if (logger != null) {
			logger.writeRaw(event.toString());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see jnzb.control.events.EventProcessor#debug(java.lang.String)
	 */
	@Override
	public void debug(String msg) {
		if (this.currentLevel >= DEBUG_LEVEL) {
			addEvent(new Event(msg, EventType.Debug));
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see jnzb.control.events.EventProcessor#error(java.lang.String)
	 */
	@Override
	public void error(String msg) {
		if (this.currentLevel >= ERROR_LEVEL) {
			addEvent(new Event(msg, EventType.Error));
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see jnzb.control.events.EventProcessor#info(java.lang.String)
	 */
	@Override
	public void info(String msg) {
		if (this.currentLevel >= INFO_LEVEL) {
			addEvent(new Event(msg, EventType.Info));
		}

	}

	public void setLevel(int level) {
		this.currentLevel = level;
	}

}
